package com.tianlh.quartz;

import java.text.ParseException;
import java.util.Date;

import org.quartz.CronExpression;
import org.quartz.CronTrigger;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.StatefulJob;
import org.springframework.stereotype.Component;

/**
 * @author 黑子
 * @Date 2018/2/28 15:23
 */
@Component
public class CountJobEntry implements StatefulJob {

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        Scheduler scheduler = jobExecutionContext.getScheduler();
        JobDetail jobDetail = jobExecutionContext.getJobDetail();
        CronTrigger trigger = (CronTrigger)jobExecutionContext.getTrigger();
        JobDataMap jobDataMap = jobDetail.getJobDataMap();
        String jobName = jobDetail.getKey().getName();
        try {
            Object value = jobDataMap.get("key");
            Integer count = Integer.valueOf(jobDataMap.get("count").toString());
            System.out.println("任务第" + count + "次执行！key = " + value + ", cron: " + trigger.getCronExpression());
            if (count == 15) {
                JobHelper.removeJob(scheduler, jobName);
                System.out.println(jobName + "任务已经删除");
            } else if (count == 10) {
                JobHelper.modifyTriggerTime(scheduler, trigger.getKey().getName(), "0/10 * * * * ?");
                System.out.println(jobName + "任务调度时间已经更改为：10s( 0/10 * * * * ? by Trigger)！");
            } else if (count == 5) {
                JobHelper.modifyJobTime(scheduler, jobDetail.getKey().getName(), "0/15 * * * * ?");
                System.out.println(jobName + "任务调度时间已经更改为：15s( 0/15 * * * * ? by Job)！");
            }
            count++;
            jobDataMap.put("count", count);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws ParseException {
        CronExpression expression = new CronExpression("0/10 * * * * ?");
        System.out.println(expression.getExpressionSummary());
        System.out.println(expression.getNextValidTimeAfter(new Date()));
    }


}
